<template>
    <div>
        <!-- 日期选择 -->
        <div>
            <el-form class="flex py-4 pl-4 bg-white border border-sky-100">
                <el-form-item label="分类名称">
                    <el-input v-model="searchCateogryName" placeholder="请输入" style="width: 200px;" />
                </el-form-item>
                <el-form-item label="创建日期" class="ml-4">
                    <!-- 日期选择组件（区间选择） -->
                    <el-date-picker v-model="pickDate" @change="datepickerChange" :shortcuts="shortcuts" type="daterange"
                        range-separator="至" start-placeholder="Start Time" end-placeholder="End Time" size="default" />
                </el-form-item>
                <el-button type="primary" :icon="Search" class="ml-4" @click="onSubmit">查询</el-button>
                <el-button class="ml-4" :icon="RefreshRight" @click="onReset">重置</el-button>
            </el-form>
        </div>
        <!-- 分类列表 -->
        <div class="mt-4 bg-white border border-sky-100 pt-4 ">
            <!-- 新增按钮 -->
            <div class="mb-4 pl-4">
                <el-button type="primary" @click="showAddCategoryDialog">
                    <el-icon class="mr-1">
                        <Plus />
                    </el-icon>
                    新增</el-button>
            </div>
            <!-- 表格 -->
            <el-table class="ml-4" :data="tableData" border stripe style="width: 90%" v-loading="tableLoading">
                <el-table-column prop="name" label="分类名称" width="180" />
                <el-table-column prop="createTime" label="创建时间" width="180" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button @click="toDelete(scope.row)" type="danger" size="small">
                            <el-icon class="mr-1">
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <div class="mt-10 mb-4 flex justify-center w-full">
                <el-pagination v-model:current-page="current" v-model:page-size="size" :page-sizes="[5, 10, 20]"
                    @size-change="pageSizeChange" @current-change="currentPageChange" :small="false" :background="true"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" class="" />
            </div>
        </div>

        <!-- <el-dialog v-model="addCategoryDialogVisible" title="新增分类" width="40%" :draggable="true"
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="formValue" :rules="rules">
                <el-form-item prop="name" label="分类名称" label-width="80px">
                    
                    <el-input v-model="formValue.name" size="large" placeholder="请输入分类名称" maxlength="20" show-word-limit
                        clearable />
                </el-form-item>
                <el-form-item label-width="80px" class="mt-4 place-content-end">
                    <div class="w-full flex flex-row-reverse">
                        <el-button @click="addCategoryDialogVisible = false" class="ml-4">取消</el-button>
                        <el-button type="primary" @click="addCategory">提交</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog> -->

        <FormDialog ref="formDialogRef" title="新增分类" @submit="addCategory" confirm-text="新增">
            <el-form ref="formRef" :rules="rules" :model="formValue">
                    <el-form-item label="分类名称" prop="name" label-width="80px" size="large">
                        <el-input v-model="formValue.name" placeholder="请输入分类名称" maxlength="20" show-word-limit clearable/>
                    </el-form-item>
                </el-form>
        </FormDialog>

    </div>
</template>

<script setup>
import { Search, RefreshRight } from '@element-plus/icons-vue';
import { showConfirm, showMessage } from '@/composables/utils';
import { ref, reactive, onBeforeMount } from 'vue';
import moment from 'moment';
import { deleteCategory, getCategoryPageList, submmitAddCategory } from '@/api/admin/category';
import FormDialog from '@/components/FormDialog.vue';
// 查询的分类名称
const searchCateogryName = ref('');
// 日期(过滤条件)
const pickDate = ref('');
//表格数据
const tableData = ref([])
//========================分页数据========================
// 当前页码，给了一个默认值 1
const current = ref(1)
// 总数据量，给了个默认值 0
const total = ref(0)
// 每页显示的数据量，给了个默认值 10
const size = ref(5)
//提交查询分类事件
//loading
const tableLoading = ref(false)
const onSubmit = () => {
    //显示表格 loading
    tableLoading.value = true
    getCategoryPageList({
        name: searchCateogryName.value,
        startDate: startDate.value,
        endDate: endDate.value,
        current: current.value,
        size: size.value
    }).then(res => {
        if (res.success) {
            tableData.value = res.data
            total.value = res.total
            current.value = res.current
            size.value = res.size
        }
    }).finally(() => {
        tableLoading.value = false
    })
}
// 进入页面的时候获取一次数据
onBeforeMount(() => {
    onSubmit()
})
// 页码改变事件
const currentPageChange = (val) => {
    console.log("当前页码: " + val)
    current.value = val
    onSubmit()
}
// 页码大小改变事件
const pageSizeChange = (val) => {
    console.log("当前页码大小: " + val)
    size.value = val
    onSubmit()
}
const onReset = () => {     //重置查询条件
    searchCateogryName.value = ''
    pickDate.value = ''
    startDate.value = ''
    endDate.value = ''
    size.value = 5
    current.value = 1
}
//======================新增分类==========================
const formRef = ref(null)
const formValue = reactive({
    name: ''
})
const rules = {
    name: [
        {
            required: true,
            message: '分类名称不能为空',
            trigger: 'blur',
        },
        { min: 1, max: 20, message: '分类名称字数要求大于 1 个字符，小于 20 个字符', trigger: 'blur' },
    ]
}
// const addCategoryDialogVisible = ref(false)
const formDialogRef = ref(null)
const showAddCategoryDialog = () => {
    formDialogRef.value.showDialog()
}
const addCategory = () => {
    //表单校验
    formRef.value.validate((valid) => {
        if (!valid) {
            console.log('form information formatter does not matched')
            return false
        }
        //发起异步请求
        submmitAddCategory(formValue).then((res) => {
            if (res.success == true) {
                showMessage('新增分类成功！', 'success')
                formDialogRef.value.closeDialog()   //关闭弹窗
                //刷新表格
                formValue.name = ''
                onSubmit()  //刷新表格
            } else {
                let message = res.message
                showMessage(message, 'error')    //错误提示
            }
        }).finally(() => {
            
        })
    })
}
//======================删除分类==========================
const toDelete = (row) => {
    //弹出确认confirm
    showConfirm('确定要删除该分类吗').then(() => {
        //发起异步请求
        deleteCategory(row.id).then((res) => {
            if(res.success == true) {
                showMessage('删除成功！', 'success')
                onSubmit()
            } else {
                let message = res.message
                showMessage(message, 'error')
            }
        })
    }).catch(() => {
        
    })
}










//====================== 日期选择事件 ======================
const startDate = reactive({})
const endDate = reactive({})
const datepickerChange = (e) => {
    startDate.value = moment(e[0]).format('YYYY-MM-DD')
    endDate.value = moment(e[1]).format('YYYY-MM-DD')
    console.log('startTime:' + startDate.value + 'endTime:' + endDate.value)
}
//日期shotscut
const shortcuts = [
    {
        text: 'Today',
        value: new Date(),
    },
    {
        text: 'Yesterday',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24);
            return [start, end];
        },
    },
    {
        text: 'A week ago',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            return [start, end];
        },
    },
];
</script>

<style scoped>
.el-form-item {
    margin-bottom: 0;
}
</style>